package com.secneo.appshare.api.impl;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URL;
import java.util.Map;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.MultipartPostMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.multipart.FilePart;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONObject;

import android.util.Log;

import com.secneo.appshare.common.Constants;

public class HttpComm {
	
	private static final String TAG = "HttpComm";
	public static String URL = Constants.URL;
	private static final int CONNECTION_TIMEOUT = 20000;
	
	public static JSONObject sendJSONToServer(String paramString, JSONObject jsonObject, int timeout) {
		try {
		
			String url = String.valueOf(URL) + paramString;
			Log.d(TAG, "Url is " + url);
			URI uri = new URL(url).toURI();
		
			HttpPost httpPost = new HttpPost(uri);
			byte[] httpPostBytes = jsonObject.toString().getBytes();
			String tmp = new String(httpPostBytes) ;
			ByteArrayEntity byteArrayEntity = new ByteArrayEntity(httpPostBytes);
			Log.d(TAG, "bytearray:" + new String(httpPostBytes));
			byteArrayEntity.setContentType("application/json");
			httpPost.setEntity(byteArrayEntity);
			DefaultHttpClient httpClient = new DefaultHttpClient();
			
			
			HttpParams httpParams = httpClient.getParams();
			HttpConnectionParams.setSocketBufferSize(httpParams, 8192);
			
			
			HttpConnectionParams.setConnectionTimeout(httpParams, timeout);
			HttpConnectionParams.setSoTimeout(httpParams, timeout);
			
			Log.d(TAG, "execute Http locahost");
			HttpResponse localObject = httpClient.execute(httpPost);
			Log.d(TAG, "execute Http locahost finished " + localObject.getStatusLine().getStatusCode() );
			if (((HttpResponse)localObject).getStatusLine().getStatusCode() != 200) {
				int statusCode = ((HttpResponse)localObject).getStatusLine().getStatusCode() ;
				Log.d(TAG, "error");
				return null;
			}
			StringBuilder builder = new StringBuilder(); 
			InputStreamReader is = new InputStreamReader(localObject.getEntity().getContent());
            BufferedReader bufferedReader2 = new BufferedReader(is);
            
            for (String s = bufferedReader2.readLine(); s != null; s = bufferedReader2.readLine()) { 
            	builder.append(s);
            }
            Log.d(TAG, ">>>>>>" + builder.toString());		
            JSONObject retJsonObject = new JSONObject(builder.toString());
			return retJsonObject;
			
		} catch (Exception ex) {
			Log.d(TAG, "error: "+ex.getMessage());
			return null;
		}
	}
	
	
	public static JSONObject doPost(String httpaction, Map<String, String> parameters) {
		String url = httpaction;
		Log.d("HttpComm", "=== doPost avatar url= "+url);
		 JSONObject retJsonObject=null;
        HttpClient client = new HttpClient();
        HttpMethod method = new PostMethod(url);
        NameValuePair [] params = new NameValuePair [parameters.size()];
        //set Http Post data
        try{
	        if (params != null) {
	        	int i =0;
	            for (Map.Entry<String, String> entry : parameters.entrySet()) {
	            	params[i++] = new NameValuePair(entry.getKey(),entry.getValue());
	            }
	            ((PostMethod)method).setRequestBody(params);
	        }
            client.executeMethod(method);
            if (method.getStatusCode() == HttpStatus.SC_OK) {
            	retJsonObject = new JSONObject( method.getResponseBodyAsString());
            	Log.d("HttpComm", ">>> doPost ret = "+retJsonObject.getString("status"));
            }
        } catch (Exception e) {
        	e.printStackTrace();
        	retJsonObject = null;
        } finally {
                method.releaseConnection();
        }
        return retJsonObject;
	}
	
	@SuppressWarnings("deprecation")
	public static JSONObject uploadFile(String httpaction , File f,String uId){
		String url = httpaction;
		 JSONObject retJsonObject=null;
		HttpClient client = new HttpClient();
		MultipartPostMethod method = new MultipartPostMethod(url);
		try {
			Log.v("myTag",f.getName());
			//method.addParameter("avatarFile", f.getName(),f);
			method.addParameter("userId",uId);
			method.addParameter("avatar","0");
			FilePart part1 = new FilePart("avatarFile",f);
			method.addPart(part1);
			client.executeMethod(method);
            if (method.getStatusCode() == HttpStatus.SC_OK) {
            	retJsonObject = new JSONObject( method.getResponseBodyAsString());
            }
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}finally{
			method.releaseConnection();
		}
		return retJsonObject;
	}
	

	public static String httpGet(String url, String vm) throws Exception {
		String responseData = null;

		if (vm != null && !vm.equals("")) {
			url += "?" + vm;
		}

		HttpClient httpClient = new HttpClient();
		GetMethod httpGet = new GetMethod(url);
		httpGet.getParams().setParameter("http.socket.timeout",
				new Integer(CONNECTION_TIMEOUT));

		try {
			int statusCode = httpClient.executeMethod(httpGet);
			if (statusCode != HttpStatus.SC_OK) {
				System.err.println("HttpGet Method failed: "
						+ httpGet.getStatusLine());
			}
			// Read the response body.
			responseData = httpGet.getResponseBodyAsString();
		} catch (Exception e) {
			throw new Exception(e);
		} finally {
			httpGet.releaseConnection();
			httpClient = null;
		}

		return responseData;
	}
	
}
